<?php
namespace App\Common\Helper;

use vendor\Cache;

class CacheHelper
{

    /**
     * 获取并缓存
     * @param string $key 缓存键
     * @param \Closure $func 获取缓存内容的匿名函数
     * @param int $expire 缓存时间
     * @param bool $isArray 是否为数组
     * @return false|mixed|string
     */
    public static function remember($key, \Closure $func, $expire = 60, $isArray = true)
    {
        $isExists = Cache::getInstance()->has($key);
        if(!$isExists){
            $rawResult = call_user_func($func);
            // 如果是数组，则序列化
            $result = $rawResult;
            $isArray && $result = json_encode($rawResult);
            Cache::getInstance()->write($key, $result, $expire);

            return $rawResult;
        }
        $result = Cache::getInstance()->get($key);

        $isArray && $result = json_decode($result, true);

        return $result;
    }
}